package com.wgb.movie.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wgb.movie.annotation.AuthCheck;
import com.wgb.movie.common.BaseResponse;
import com.wgb.movie.common.DeleteRequest;
import com.wgb.movie.common.ErrorCode;
import com.wgb.movie.common.ResultUtils;
import com.wgb.movie.constant.UserConstant;
import com.wgb.movie.exception.BusinessException;
import com.wgb.movie.exception.ThrowUtils;
import com.wgb.movie.mapper.MovieShowMapper;
import com.wgb.movie.model.dto.movieOrder.MovieOrderAddRequest;
import com.wgb.movie.model.dto.movieOrder.MovieOrderEditRequest;
import com.wgb.movie.model.dto.movieOrder.MovieOrderQueryRequest;
import com.wgb.movie.model.dto.movieOrder.MovieOrderUpdateRequest;
import com.wgb.movie.model.entity.MovieOrder;
import com.wgb.movie.model.entity.MovieShow;
import com.wgb.movie.model.entity.SeatStatus;
import com.wgb.movie.model.entity.User;
import com.wgb.movie.model.vo.MovieOrderVO;
import com.wgb.movie.service.MovieOrderService;
import com.wgb.movie.service.MovieShowService;
import com.wgb.movie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 订单接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/movieOrder")
@Slf4j
public class MovieOrderController {

    @Resource
    private MovieOrderService movieOrderService;

    @Resource
    private UserService userService;

    @Resource
    private MovieShowService movieShowService;

    // region 增删改查

    /**
     * 创建订单
     *
     * @param movieOrderAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addMovieOrder(@RequestBody MovieOrderAddRequest movieOrderAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(movieOrderAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        MovieOrder movieOrder = new MovieOrder();
        BeanUtils.copyProperties(movieOrderAddRequest, movieOrder);
        movieOrder.setOrderStatus(0);
        movieOrder.setSeat(JSONUtil.toJsonStr(movieOrderAddRequest.getSeat()));
        // 数据校验
        movieOrderService.validMovieOrder(movieOrder, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        movieOrder.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = movieOrderService.save(movieOrder);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        //修改上映表
        MovieShow movieShow = movieShowService.getById(movieOrder.getMovieShowId());
        List<SeatStatus> seatStatuses = JSONUtil.toList(movieShow.getSeats(), SeatStatus.class);
        for (SeatStatus seatStatus : seatStatuses) {
            if (seatStatus.getRow().equals(movieOrderAddRequest.getSeat().getRow()) &&
                    seatStatus.getColumn().equals(movieOrderAddRequest.getSeat().getColumn())) {
                seatStatus.setStatus(1);
            }
        }
        movieShow.setSeats(JSONUtil.toJsonStr(seatStatuses));
        boolean update = movieShowService.updateById(movieShow);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newMovieOrderId = movieOrder.getId();
        return ResultUtils.success(newMovieOrderId);
    }

    /**
     * 删除订单
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteMovieOrder(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        MovieOrder oldMovieOrder = movieOrderService.getById(id);
        ThrowUtils.throwIf(oldMovieOrder == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldMovieOrder.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = movieOrderService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        //修改上映表
        SeatStatus status = JSONUtil.toBean(oldMovieOrder.getSeat(), SeatStatus.class);
        MovieShow movieShow = movieShowService.getById(oldMovieOrder.getMovieShowId());
        List<SeatStatus> seatStatuses = JSONUtil.toList(movieShow.getSeats(), SeatStatus.class);
        for (SeatStatus seatStatus : seatStatuses) {
            if (seatStatus.getRow().equals(status.getRow()) &&
                    seatStatus.getColumn().equals(status.getColumn())) {
                seatStatus.setStatus(0);
            }
        }
        movieShow.setSeats(JSONUtil.toJsonStr(seatStatuses));
        boolean update = movieShowService.updateById(movieShow);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新订单（仅管理员可用）
     *
     * @param movieOrderUpdateRequest
     * @return
     */
//    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Boolean> updateMovieOrder(@RequestBody MovieOrderUpdateRequest movieOrderUpdateRequest) {
//        if (movieOrderUpdateRequest == null || movieOrderUpdateRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        // todo 在此处将实体类和 DTO 进行转换
//        MovieOrder movieOrder = new MovieOrder();
//        BeanUtils.copyProperties(movieOrderUpdateRequest, movieOrder);
//        // 数据校验
//        movieOrderService.validMovieOrder(movieOrder, false);
//        // 判断是否存在
//        long id = movieOrderUpdateRequest.getId();
//        MovieOrder oldMovieOrder = movieOrderService.getById(id);
//        ThrowUtils.throwIf(oldMovieOrder == null, ErrorCode.NOT_FOUND_ERROR);
//        // 操作数据库
//        boolean result = movieOrderService.updateById(movieOrder);
//        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
//        return ResultUtils.success(true);
//    }

    /**
     * 根据 id 获取订单（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<MovieOrderVO> getMovieOrderVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        MovieOrder movieOrder = movieOrderService.getById(id);
        ThrowUtils.throwIf(movieOrder == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(movieOrderService.getMovieOrderVO(movieOrder, request));
    }

    /**
     * 分页获取订单列表（仅管理员可用）
     *
     * @param movieOrderQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MovieOrder>> listMovieOrderByPage(@RequestBody MovieOrderQueryRequest movieOrderQueryRequest) {
        long current = movieOrderQueryRequest.getCurrent();
        long size = movieOrderQueryRequest.getPageSize();
        // 查询数据库
        Page<MovieOrder> movieOrderPage = movieOrderService.page(new Page<>(current, size),
                movieOrderService.getQueryWrapper(movieOrderQueryRequest));
        return ResultUtils.success(movieOrderPage);
    }

    /**
     * 分页获取订单列表（封装类）
     *
     * @param movieOrderQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<MovieOrderVO>> listMovieOrderVOByPage(@RequestBody MovieOrderQueryRequest movieOrderQueryRequest,
                                                                   HttpServletRequest request) {
        long current = movieOrderQueryRequest.getCurrent();
        long size = movieOrderQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<MovieOrder> movieOrderPage = movieOrderService.page(new Page<>(current, size),
                movieOrderService.getQueryWrapper(movieOrderQueryRequest));
        // 获取封装类
        return ResultUtils.success(movieOrderService.getMovieOrderVOPage(movieOrderPage, request));
    }

    /**
     * 分页获取当前登录用户创建的订单列表
     *
     * @param movieOrderQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<MovieOrderVO>> listMyMovieOrderVOByPage(@RequestBody MovieOrderQueryRequest movieOrderQueryRequest,
                                                                     HttpServletRequest request) {
        ThrowUtils.throwIf(movieOrderQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        movieOrderQueryRequest.setUserId(loginUser.getId());
        long current = movieOrderQueryRequest.getCurrent();
        long size = movieOrderQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<MovieOrder> movieOrderPage = movieOrderService.page(new Page<>(current, size),
                movieOrderService.getQueryWrapper(movieOrderQueryRequest));
        // 获取封装类
        return ResultUtils.success(movieOrderService.getMovieOrderVOPage(movieOrderPage, request));
    }

    /**
     * 编辑订单（给用户使用）
     *
     * @param movieOrderEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editMovieOrder(@RequestBody MovieOrderEditRequest movieOrderEditRequest, HttpServletRequest request) {
        if (movieOrderEditRequest == null || movieOrderEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        MovieOrder movieOrder = new MovieOrder();
        BeanUtils.copyProperties(movieOrderEditRequest, movieOrder);
        // 数据校验
        movieOrderService.validMovieOrder(movieOrder, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = movieOrderEditRequest.getId();
        MovieOrder oldMovieOrder = movieOrderService.getById(id);
        ThrowUtils.throwIf(oldMovieOrder == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldMovieOrder.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = movieOrderService.updateById(movieOrder);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        //修改show
        if(movieOrderEditRequest.getOrderStatus()==2){
            MovieShow movieShow = movieShowService.getById(oldMovieOrder.getMovieShowId());
            SeatStatus status =JSONUtil.toBean(oldMovieOrder.getSeat(), SeatStatus.class);
            List<SeatStatus> seatStatuses = JSONUtil.toList(movieShow.getSeats(), SeatStatus.class);
            for (SeatStatus seatStatus : seatStatuses) {
                if (seatStatus.getRow().equals(status.getRow()) &&
                        seatStatus.getColumn().equals(status.getColumn())) {
                    seatStatus.setStatus(0);
                }
            }
            movieShow.setSeats(JSONUtil.toJsonStr(seatStatuses));
            boolean update = movieShowService.updateById(movieShow);
            ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(true);
    }

    // endregion
}
